package com.stormrage.edu.serv.learn.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.stormrage.constants.ErrCons;
import com.stormrage.edu.dao.exam.ExmScorePercentDao;
import com.stormrage.edu.dao.exam.ExmRelateCountDao;
import com.stormrage.edu.dao.learn.LeaBunchDao;
import com.stormrage.edu.dao.learn.LeaTermDao;
import com.stormrage.edu.serv.edu.EduCourseServ;
import com.stormrage.edu.serv.edu.EduMajorServ;
import com.stormrage.edu.serv.edu.EduModuleServ;
import com.stormrage.edu.serv.edu.impl.EduModuleServImpl;
import com.stormrage.edu.serv.exam.ExmScorePercentServ;
import com.stormrage.edu.serv.exam.ExmTermScoreServ;
import com.stormrage.edu.serv.learn.LeaBunchOperServ;
import com.stormrage.edu.serv.learn.LeaBunchUsuaServ;
import com.stormrage.edu.serv.learn.LeaTermNessServ;
import com.stormrage.edu.serv.learn.LeaTermServ;
import com.stormrage.entity.edu.EduCourse;
import com.stormrage.entity.edu.EduMajor;
import com.stormrage.entity.edu.EduModule;
import com.stormrage.entity.exam.ExmScorePercent;
import com.stormrage.entity.exam.ExmTermScore;
import com.stormrage.entity.exam.ExmRelateCount;
import com.stormrage.entity.learn.LeaBunch;
import com.stormrage.entity.learn.LeaBunchOper;
import com.stormrage.entity.learn.LeaBunchUsua;
import com.stormrage.entity.learn.LeaTerm;
import com.stormrage.entity.learn.LeaTermNess;
import com.stormrage.entity.learn.rep.LeaTermRep;
import com.stormrage.entity.learn.req.ExmTermNessReq;
import com.stormrage.entity.learn.req.LeaTermCreateReq;
import com.stormrage.entity.learn.req.LeaTermReq;
import com.stormrage.entity.rep.ListRep;
import com.stormragetech.core.exception.StormrageTechException;
import com.stormragetech.core.util.DateUtil;
import com.stormragetech.core.util.NumberUtil;

/**
 * @Title: LeaTermServImpl.java
 * @Package com.stormrage.edu.serv.learn.impl
 * @Description: 学期 Service
 * @author www.stormragetech.com
 * @date 2016年4月13日
 * @version V1.0
 */
@Service
public class LeaTermServImpl implements LeaTermServ {

	private static final Logger logger = LoggerFactory.getLogger(EduModuleServImpl.class);

	@Autowired
	private ExmRelateCountDao exmRelateExamDao;

	@Autowired
	private ExmScorePercentDao exmScorePercentDao;

	@Autowired
	private LeaBunchDao leaBunchDao;

	@Autowired
	private LeaTermDao leaTermDao;

	@Autowired
	private EduCourseServ eduCourseServ;

	@Autowired
	private EduMajorServ eduMajorServ;

	@Autowired
	private EduModuleServ eduModuleServ;

	@Autowired
	private ExmScorePercentServ exmScorePercentServ;

	@Autowired
	private ExmTermScoreServ exmTermScoreServ;

	@Autowired
	private LeaBunchOperServ leaBunchOperServ;

	@Autowired
	private LeaBunchUsuaServ leaBunchUsuaServ;

	@Autowired
	private LeaTermNessServ leaTermNessServ;

	@Override
	public Integer create(final LeaTerm arg0) throws StormrageTechException {

		logger.debug(" 【 Serv 】- 【 LeaTermServ 】- 【 create 】- 开始运行 ");

		Integer index = leaTermDao.create(arg0);

		logger.debug(" 【 Serv 】- 【 LeaTermServ 】- 【 create 】- 完成运行 ");
		return index;

	}

	@Override
	public Integer create(final LeaTermCreateReq arg0) throws StormrageTechException {

		logger.debug(" 【 Serv 】- 【 LeaTermServ 】- 【 Create 】- 开始运行 ");

		// ------------------ 判断学期是否创建重复 ------------------
		LeaTerm term = queryByMajorIdDate(arg0.getMajorId());
		if (null != term)
			throw StormrageTechException.instance(ErrCons.SERV_ERR, "以创建此专业学期", StormrageTechException.ERR_APP,
					"【 LeaTermServ 】-【 Create 】");

		// ------------------ 创建学期 ------------------
		LeaTerm entity = LeaTerm.instance(arg0);
		Integer index = leaTermDao.create(entity);

		// ------------------ 添加学期默认散员班级 ------------------
		String name = "bunch" + DateUtil.dateToStr(new Date(), "yyyy") + NumberUtil.initZero(arg0.getMajorId(), 4)
				+ NumberUtil.initZero(index, 5);
		LeaBunch bunch = LeaBunch.instance(null, name, index, 0, 0);
		Integer bunchId = leaBunchDao.create(bunch);

		entity.setId(index);
		entity.setBunch(bunchId);
		leaTermDao.update(entity);

		// ------------------ 添加班级成绩 ------------------
		LeaBunchOper bunchOper = LeaBunchOper.instance(index);
		LeaBunchUsua bunchUsua = LeaBunchUsua.instance(index);
		leaBunchOperServ.create(bunchOper);
		leaBunchUsuaServ.create(bunchUsua);

		// ------------------ 创建成绩比例 ------------------
		ExmScorePercent score = ExmScorePercent.instance(arg0, index);
		exmScorePercentDao.create(score);

		// ------------------ 创建学期成绩 ------------------
		ExmTermScore termScore = ExmTermScore.instance(arg0, index);
		exmTermScoreServ.create(termScore);

		// ------------------ 获取专业信息，生成学期关联分数、数量 ------------------
		EduMajor major = eduMajorServ.queryById(arg0.getMajorId());

		// ------------------ 单一模组，绑定课程 ------------------
		if (major.getModule().equals(0)) {

			ExmTermNessReq req = ExmTermNessReq.instance(index, 0);
			List<EduCourse> list = eduCourseServ.queryRepListByTerm(req);

			// ------------------ 绑定课程 ------------------
			Iterator<EduCourse> it = list.iterator();
			while (it.hasNext()) {
				EduCourse course = it.next();
				ExmRelateCount relate = ExmRelateCount.instance(index, course.getId(), 0);
				exmRelateExamDao.create(relate);
			}

			// ------------------ 创建选课数量 ------------------
			LeaTermNess ness = LeaTermNess.instance(index, arg0.getNess());
			leaTermNessServ.create(ness);

		}
		// ------------------ 多模组，绑定模组 ------------------
		if (major.getModule().equals(1)) {

			ExmTermNessReq req = ExmTermNessReq.instance(index, 0);
			List<EduModule> list = eduModuleServ.queryRepListByTerm(req);

			Iterator<EduModule> it = list.iterator();
			while (it.hasNext()) {
				EduModule module = it.next();
				ExmRelateCount relate = ExmRelateCount.instance(index, module.getId(), 1);
				exmRelateExamDao.create(relate);
			}

		}

		logger.debug(" 【 Serv 】- 【 LeaTermServ 】- 【 Create 】- 完成运行 ");
		return index;

	}

	@Override
	public void update(final LeaTerm arg0) throws StormrageTechException {

		logger.debug(" 【 Serv 】- 【 LeaTermServ 】- 【 Update 】- 开始运行 ");

		leaTermDao.update(arg0);

		logger.debug(" 【 Serv 】- 【 LeaTermServ 】- 【 Update 】- 完成运行 ");

	}

	@Override
	public void delete(final Integer arg0) throws StormrageTechException {

		logger.debug(" 【 Serv 】- 【 LeaTermServ 】- 【 Delete 】- 开始运行 ");

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", arg0);

		leaTermDao.delete(map);
		leaBunchDao.deleteByTermId(map);

		logger.debug(" 【 Serv 】- 【 LeaTermServ 】- 【 Delete 】- 完成运行 ");

	}

	@Override
	public Integer queryCount(final LeaTermReq arg0) throws StormrageTechException {

		logger.debug(" 【 Serv 】- 【 LeaTermServ 】- 【 QueryCount 】- 开始运行 ");

		Map<String, Object> map = initQuery(arg0);

		Integer count = leaTermDao.queryCount(map);

		logger.debug(" 【 Serv 】- 【 LeaTermServ 】- 【 QueryCount 】- 完成运行 ");
		return count;

	}

	@Override
	public Integer queryRepCount(final LeaTermReq arg0) throws StormrageTechException {

		logger.debug(" 【 Serv 】- 【 LeaTermServ 】- 【 QueryCount 】- 开始运行 ");

		Map<String, Object> map = initQuery(arg0);

		Integer count = leaTermDao.queryRepCount(map);

		logger.debug(" 【 Serv 】- 【 LeaTermServ 】- 【 QueryCount 】- 完成运行 ");
		return count;

	}

	@Override
	public LeaTerm queryById(final Integer arg0) throws StormrageTechException {

		logger.debug(" 【 Serv 】- 【 EduChapterServ 】- 【 QueryById 】- 开始运行 ");

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", arg0);

		LeaTerm entity = leaTermDao.queryById(map);

		logger.debug(" 【 Serv 】- 【 EduChapterServ 】- 【 QueryById 】- 完成运行 ");
		return entity;

	}

	@Override
	public LeaTerm queryByMajorIdDate(final Integer arg0) throws StormrageTechException {

		logger.debug(" 【 Serv 】- 【 EduChapterServ 】- 【 QueryByMajorIdDate 】- 开始运行 ");

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("majorId", arg0);

		LeaTerm entity = leaTermDao.queryByMajorIdDate(map);

		logger.debug(" 【 Serv 】- 【 EduChapterServ 】- 【 QueryByMajorIdDate 】- 完成运行 ");
		return entity;

	}

	@Override
	public List<LeaTerm> queryList() throws StormrageTechException {

		logger.debug(" 【 Serv 】- 【 EduChapterServ 】- 【 QueryList 】- 开始运行 ");

		List<LeaTerm> array = leaTermDao.queryList();

		logger.debug(" 【 Serv 】- 【 EduChapterServ 】- 【 QueryList 】- 完成运行 ");
		return array;

	}

	@Override
	public List<LeaTermRep> queryRepListForExam() throws StormrageTechException {

		logger.debug(" 【 Serv 】- 【 LeaTermServ 】- 【 queryRepListForExam 】-【 STARTED 】");

		List<LeaTermRep> array = leaTermDao.queryRepListForExam();
		int seq = 1;

		Iterator<LeaTermRep> it = array.iterator();
		while (it.hasNext()) {
			LeaTermRep entity = it.next();

			ExmScorePercent perc = exmScorePercentServ.queryByTermId(entity.getId());
			String state = "已设置";

			if (null == perc)
				state = "未设置";
			else if (!Integer.valueOf(perc.getExam() + perc.getOper() + perc.getUsua()).equals(100))
				state = "未设置";

			entity = LeaTermRep.instance(entity, seq, state);
			seq++;
		}

		logger.debug(" 【 Serv 】- 【 LeaTermServ 】- 【 queryRepListForExam 】-【 COMPLETED 】");
		return array;

	}

	@Override
	public ListRep queryRepList(final LeaTermReq arg0) throws StormrageTechException {

		logger.debug(" 【 Serv 】- 【 LeaTermServ 】- 【 QueryRepList 】- 开始运行 ");

		Map<String, Object> map = initQuery(arg0);

		Integer count = leaTermDao.queryCount(map);

		List<LeaTermRep> array = leaTermDao.queryRepList(map);
		int seq = arg0.getPage().getStartPage() + 1;

		Iterator<LeaTermRep> it = array.iterator();
		while (it.hasNext()) {
			LeaTermRep term = it.next();

			term = LeaTermRep.instance(term, seq);
			seq++;
		}

		ListRep rep = ListRep.instance(count, array);

		logger.debug(" 【 Serv 】- 【 LeaTermServ 】- 【 QueryRepList 】- 完成运行 ");
		return rep;

	}

	private Map<String, Object> initQuery(final LeaTermReq arg0) {

		if (null == arg0)
			return null;

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("startPage", arg0.getPage().getStartPage());
		map.put("size", arg0.getPage().getSize());

		StringBuffer query = new StringBuffer("");

		if (null != arg0.getTerm() && arg0.getTerm().length() > 0) {
			query.append("a.term LIKE :term AND ");
			map.put("term", "%" + arg0.getTerm() + "%");
		}

		if (null != arg0.getTerm() && arg0.getTerm().length() > 0) {
			query.append("b.major LIKE :major AND ");
			map.put("term", "%" + arg0.getTerm() + "%");
		}

		if (null != arg0.getApplyDateStart()) {
			query.append("a.apply_date_start >= :applyDateStart AND a.apply_date_end <= :applyDateEnd AND ");
			map.put("applyDateStart", arg0.getApplyDateStart());
			map.put("applyDateEnd", arg0.getApplyDateEnd());
		}

		if (null != arg0.getStudyDateStart()) {
			query.append("a.study_date_start >= :studyDateStart AND a.study_date_end <= :studyDateEnd AND ");
			map.put("studyDateStart", arg0.getStudyDateStart());
			map.put("studyDateEnd", arg0.getStudyDateEnd());
		}

		if (null != arg0.getExamDateStart()) {
			query.append("a.exam_date_start >= :examDateStart AND a.exam_date_end <= :examDateEnd AND ");
			map.put("examDateStart", arg0.getExamDateStart());
			map.put("examDateEnd", arg0.getExamDateEnd());
		}

		String sql = query.toString();
		if (null != sql && sql.length() > 0)
			map.put("query", " AND " + sql.substring(0, sql.length() - 4));
		else
			map.put("query", "");

		return map;
	}

}
